--
-- Author: shineflag
-- Date: 2018-04-02 09:36:56
--

local skynet = require "skynet"
require("skynet.manager")
local mysql = require("skynet.db.mysql")
local log = require "log"
local json = require("json")
local names = require("tour_name")
local cluster = require("skynet.cluster")
local proto = require("json_proto")



local halls = {  --各大厅的配置情况
	-- ["hname"] = {name="xxx",host = "xxx", port = "xxx", player=0, con_status=true}
}
local pokaa_db
local mdata_proxy   --mdata
local rmoney = 0    --注册送的金币

local meta  =   {}  --本服务的私有接口
local CLIENT = {}   --客户端请求的接口
local CMD = {}      --向外提供的接口

local TAG = "LOGIND"

function meta.connect_pokaa_db()
	function meta.on_connect(db)
		db:query("set charset utf8");
		log.e(TAG, "pokaa db connected!")
	end

	local mconf = require("mysql_conf")
	pokaa_db = mysql.connect({
		host = mconf.host,
		port = mconf.port,
		database = mconf.database,
		user = mconf.user,
		password = mconf.password,
		max_packet_size=1024*1024,
		on_connect=on_connect
		})

	if not pokaa_db then
		log.e(TAG,"failed to connect db")
		skynet.exit()
	end
end


--游客注册
function meta.register_tour(data)
	--生成游客的sitemid
	local sql = string.format("INSERT INTO pokaa_register_tour (sitemid, uuid) VALUES (NULL, '%s')", data.uuid)
	local res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
	local sitemid = res.insert_id

	--生成游戏的唯一mid
	sql = string.format("INSERT INTO pokaa_sid2mid (mid, sid, sitemid) VALUES (NULL, 100, %d)", sitemid)
	res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
	local mid = res.insert_id 

	--生成用户信息
	local now = os.time()
	math.randomseed(now)
	local mnick = "guest" .. mid
	local nt = data.nt
	local ip = 0
	sql = string.format("INSERT INTO pokaa_userinfo (`mid`, `sid`, `bid`, `clienttype`, `mnick`, `sitemid`, `sex`, `nationality`, `mstatus`, `mactivetime`, `mentrydays`, `rtime`, `version`, `ip`, `devicename`, `osversion`, `nettype`, `pay`, `inviteid`) VALUES (%d, %d, %d, %d, '%s', %d, 0, '%s', '1', %d, '1', %d, '%s', '%s', '%s', '%s', '%s', '0', '0')",
		mid,100,data.bid,data.clienttype,mnick,sitemid,data.nt,now,now,data.version,ip,
		data.devicename,data.osversion,data.nettype)
	res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))

	--生成在玩数据
	sql = string.format("INSERT INTO pokaa_playinfo (mid, wtimes, ltimes, maxmoney, maxwin) VALUES (%d, 0, 0, %d, 0)", mid, rmoney)
	res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))

	--生成金币财富信息
	skynet.call(mdata_proxy,"lua", "register",mid,{money=rmoney})
	if not res.err then
		return mid 
	end

end

--根据uuid找出游客的mid
function meta.find_tour_mid(uuid)

	local sql = string.format("select sitemid from pokaa_register_tour where uuid='%s'",uuid)
	local res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
	local k,row_data = next(res)
	if not row_data or not row_data.sitemid then
		log.d(TAG,"failed sql[%s] err[%s]",sql, res.err) 
		return nil 
	end
	local sitemid = row_data.sitemid 

	sql = string.format("select mid from pokaa_sid2mid where sid=100 and sitemid=%d",sitemid)
	res = pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
	k,row_data = next(res)
	if not row_data or not row_data.mid then 
		log.d(TAG,"failed sql[%s] err[%s]",sql, res.err) 
		return nil 
	end

	local mid = row_data.mid 

	return mid 
end 

--获取用的信息
function meta.get_user_info(mid)
	local sql = string.format("SELECT mnick, sex FROM pokaa_userinfo WHERE mid=%d",mid)
	local res =  pokaa_db:query(sql)
	log.d(TAG,"after sql[%s] res[%s]",sql, json.encode(res))
	k,row_data = next(res)
	if not row_data then 
		log.d(TAG,"failed sql[%s] err[%s]",sql, res.err) 
		return nil 
	end

	local ret, rdata = 	skynet.call(mdata_proxy,"lua", "getall",mid)
	log.d(TAG,"after call redis user[%d] info ret[%s] rdata[%s] ",mid, ret,json.encode(rdata))
	if ret then 
		rdata.mnick = row_data.mnick 
		rdata.sex = row_data.sex 
		return rdata 
	else
		return nil 
	end

end

function  CLIENT.login_tour( param )
	log.d(TAG,"uuid[%s]",param.uuid)

	local mid = meta.find_tour_mid(param.uuid)
	if not mid then 
		mid = meta.register_tour(param)
	end


	local uinfo = meta.get_user_info(mid)


	local data = {}
	data.ret = 200
	data.mid =  mid -- math.random(10000,99999)
    data.mnick = uinfo.mnick
    data.money = tonumber(uinfo.money) --math.random(1000,99999)
    data.wtimes = tonumber(uinfo.wtimes) --math.random(100)
    data.ltimes = tonumber(uinfo.ltimes)  --math.random(100)
    data.secret = "gaga"
    data.icon = "icon"
    data.sex = uinfo.sex
    data.serverinfo = {host="10.0.0.100",port=6000}

    -- skynet.call(halld,"lua","login",data.mid, data.mtkey)

	return proto.create_resp("login_tour",data)
end

function CMD.client(data)
	log.d(TAG,"client data[%s]",data)
	local pkg = proto.unpack_body(data)
	local method = pkg.cmd
	local param = pkg.req

	local func = CLIENT[method] 
	if func then
		return func(param)
	else
		log.e(TAG,"not found method[%s]",method)
		return "not found page", -404
	end
end

function CMD.register(conf)
	log.e(TAG,"register conf[%s]",json.encode(conf))
	if not halls[conf.name] then 
		local hall={
			name=conf.name,
			host=conf.host,
			port=conf.port,
			player=0,
			con_status=true,
		}
		halls[conf.name] = hall
		log.e(TAG,"hall [%s] register conf[%s]",conf.name, json.encode(hall))
	else
		halls[conf.name].host = conf.host
		halls[conf.name].port = conf.port
		halls[conf.name].con_status = true 
		log.e(TAG,"hall [%s] reconnect conf[%s]",conf.name, json.encode(halls[conf.name]))
	end


end


skynet.start(function()
	rmoney = skynet.getenv "rmoney" or 0
	meta.connect_pokaa_db()
	mdata_proxy = skynet.uniqueservice "mdata"

	skynet.dispatch("lua", function(_,_,cmd,...)
		local f = CMD[cmd]
		if f then
			skynet.ret(skynet.pack(f(...)))
		end
	end)
	cluster.register("logind")
	skynet.register(".logind")

end)